package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/selectAllUser")
    public Result selectAllUser(){
        return Result.success(userService.findAllUser());
    }
    //http://127.0.0.1:8081/login?username=admin&password=123456
    @GetMapping("/login")
    public Result findUser(String username,String password){
        return Result.success(userService.login(username,password));
    }
    @PostMapping("/register")
    public Result register(User user) {
        int count = userService.register(user);
        if (count>0)
        {
            return Result.success("注册成功");
        }
        else {
            return Result.error("注册失败");
        }

    }
    //GET http://localhost:8081/findUserByEmail?email=admin@smarthome.com
    @GetMapping("/findUserByEmail")
    public Result findUserByEmail(String email) {
        User user = userService.findUserByEmail(email);

        if(user !=null){
            return Result.success(user);
        } else {
            return Result.notFound("邮箱不存在");
        }
    }
    //GET http://localhost:8081/sendEmailCode?email=3146706269@qq.com
    @GetMapping("/sendEmailCode")
    public Result sendEmailCode(String email) {
        User user = userService.findUserByEmail(email);
        if (user!= null){
            userService.sendEmailCode(email);
            return Result.success("发送成功");
        }
        return Result.notFound("邮箱号不存在");
    }
    //POST http://localhost:8081/updatePasswordByEmail?email=3146706269@qq.com&password=123456&code=123456
    @PutMapping("/updatePasswordByEmail")
    public Result updatePasswordByEmail(String email, String password,String code){
        Boolean checkCode =userService.checkCode(email, code);
        if (checkCode){
            int i =userService.updatePasswordByEmail(email, password);
            if (i>0){
                return Result.success("修改成功");
            }
            return Result.notFound("成功获取验证码");
        }
        else {
            return Result.success("验证码错误");
        }

    }
}
